import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;

public class CreateParkingArea {
    public String createParkSql(String parkName){
        String sql = String.format("CREATE TABLE %s(\n" +
                "id INT NOT NULL,\n" +
                "status VARCHAR(50) NOT NULL,\n" +
                "PRIMARY KEY (id)\n" +
                ")ENGINE=InnoDB DEFAULT CHARSET=utf8;", parkName);
        return sql;
    }

    public void createPark(String sql){
        try{
            Connection conn = DatabaseUtil.getConnection();
            Statement stmt = conn.createStatement();
            stmt.execute(sql);
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    public void insertPark(String parkName, int parkMaxPos){
        StringBuilder sql = new StringBuilder("INSERT INTO "+parkName+" (id, status) values ");
        int count = 1;
        while(count<=parkMaxPos){
            sql.append(String.format("(%d, 'empty'),", count));
            count += 1;
        }
        String sqlString = sql.toString();
        String sql2 = sqlString.substring(0, sqlString.length()-1);
        try{
            Connection conn = DatabaseUtil.getConnection();
            Statement stmt = conn.createStatement();
            stmt.execute(sql2);
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    public void initPark(String parkInfo){
        String parkName = parkInfo.split(":")[0];
        int parkMaxPos = Integer.parseInt(parkInfo.split(":")[1]);
        if(DatabaseUtil.validateTableExist(parkName)){
            DatabaseUtil.dropExistTable(parkName);
        }
        String sql = createParkSql(parkName);
        createPark(sql);
        insertPark(parkName, parkMaxPos);
    }
}
